<template>
  <div class="register-container">
    <div class="register-card">
      <!-- 头部 -->
      <div class="register-header">
        <div class="logo">
          <span class="logo-text">ZenithMind</span>
        </div>
        <h2>创建账户</h2>
        <p>加入我们，开启智能学习之旅</p>
      </div>

      <!-- 注册表单 -->
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="register-form"
        @submit.prevent="handleRegister"
      >
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            size="large"
            clearable
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱地址"
            size="large"
            clearable
          >
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 手机号 (可选) -->
        <el-form-item prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号 (可选)"
            size="large"
            clearable
          >
            <template #prefix>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            show-password
            clearable
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            size="large"
            show-password
            clearable
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item prop="captcha">
          <div class="captcha-input">
            <el-input
              v-model="registerForm.captcha"
              placeholder="请输入验证码"
              size="large"
              clearable
            >
              <template #prefix>
                <el-icon><Key /></el-icon>
              </template>
            </el-input>
            <el-button
              :disabled="captchaDisabled"
              @click="sendCaptcha"
              class="captcha-btn"
            >
              {{ captchaText }}
            </el-button>
          </div>
        </el-form-item>

        <!-- 协议同意 -->
        <el-form-item prop="agreement">
          <el-checkbox v-model="registerForm.agreement">
            我已阅读并同意
            <el-link type="primary" @click="showUserAgreement">《用户协议》</el-link>
            和
            <el-link type="primary" @click="showPrivacyPolicy">《隐私政策》</el-link>
          </el-checkbox>
        </el-form-item>

        <!-- 注册按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            @click="handleRegister"
            class="register-btn"
          >
            立即注册
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 底部链接 -->
      <div class="register-footer">
        <span>已有账户？</span>
        <el-link type="primary" @click="goToLogin">立即登录</el-link>
      </div>

      <!-- 第三方注册 -->
      <div class="social-register">
        <div class="divider">
          <span>或使用以下方式注册</span>
        </div>
        <div class="social-buttons">
          <el-button circle @click="registerWithWechat">
            <el-icon><ChatDotRound /></el-icon>
          </el-button>
          <el-button circle @click="registerWithQQ">
            <el-icon><User /></el-icon>
          </el-button>
          <el-button circle @click="registerWithGithub">
            <el-icon><Link /></el-icon>
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 返回首页按钮 -->
    <el-button 
      circle 
      @click="goHome"
      class="back-home-btn"
    >
      <el-icon><House /></el-icon>
    </el-button>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { verificationApi } from '@/api/user'
import {
  User, Message, Phone, Lock, Key,
  ChatDotRound, Link, House
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const registerFormRef = ref()
const loading = ref(false)
const captchaCountdown = ref(0)
const captchaTimer = ref(null)

// 表单数据
const registerForm = reactive({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  captcha: '',
  agreement: false
})

// 表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: '用户名只能包含字母、数字、下划线和中文', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/, message: '密码必须包含大小写字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ],
  agreement: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请阅读并同意用户协议和隐私政策'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 计算属性
const captchaDisabled = computed(() => {
  return captchaCountdown.value > 0 || !registerForm.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email)
})

const captchaText = computed(() => {
  return captchaCountdown.value > 0 ? `${captchaCountdown.value}s后重发` : '发送验证码'
})

// 方法
const sendCaptcha = async () => {
  if (!registerForm.email) {
    ElMessage.warning('请先输入邮箱地址')
    return
  }

  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email)) {
    ElMessage.warning('请输入正确的邮箱地址')
    return
  }

  try {
    await verificationApi.sendRegisterCode({
      email: registerForm.email,
      username: registerForm.username,
      type: 1 // 1:注册验证码
    })

    ElMessage.success('验证码已发送到您的邮箱')
    startCaptchaCountdown()
  } catch (error) {
    console.error('发送验证码失败:', error)
    const errorMessage = error.response?.data?.msg || '验证码发送失败，请稍后重试'
    ElMessage.error(errorMessage)
  }
}

const startCaptchaCountdown = () => {
  captchaCountdown.value = 60
  captchaTimer.value = setInterval(() => {
    captchaCountdown.value--
    if (captchaCountdown.value <= 0) {
      clearInterval(captchaTimer.value)
    }
  }, 1000)
}

const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    await registerFormRef.value.validate()
    loading.value = true

    // 调用注册API
    const registerData = {
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password,
      code: registerForm.captcha // 后端期望字段为code
    }
    
    // 调用用户服务注册接口
    const response = await userStore.register(registerData)

    ElMessage.success('注册成功！请登录您的账户')

    // 跳转到登录页
    router.push('/login')

  } catch (error) {
    console.error('注册失败:', error)
    const errorMessage = error.response?.data?.msg || error.message || '注册失败，请检查信息后重试'
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}

const goToLogin = () => {
  router.push('/login')
}

const goHome = () => {
  router.push('/')
}

const showUserAgreement = () => {
  // 显示用户协议
  ElMessage.info('用户协议功能待实现')
}

const showPrivacyPolicy = () => {
  // 显示隐私政策
  ElMessage.info('隐私政策功能待实现')
}

const registerWithWechat = () => {
  ElMessage.info('微信注册功能待实现')
}

const registerWithQQ = () => {
  ElMessage.info('QQ注册功能待实现')
}

const registerWithGithub = () => {
  ElMessage.info('GitHub注册功能待实现')
}
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: -10%;
    right: -10%;
    width: 500px;
    height: 500px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    z-index: 1;
  }
  
  &::after {
    content: '';
    position: absolute;
    bottom: -10%;
    left: -10%;
    width: 400px;
    height: 400px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    z-index: 1;
  }
}

.register-card {
  width: 100%;
  max-width: 550px;
  background: white;
  border-radius: 20px;
  padding: 50px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
  position: relative;
  z-index: 2;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 150px;
    height: 150px;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
    border-radius: 0 0 0 100%;
    z-index: -1;
  }
}

.register-header {
  text-align: center;
  margin-bottom: 40px;
  
  .logo {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 24px;
    
    .logo-text {
      font-size: 32px;
      font-weight: 700;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
  }
  
  h2 {
    font-size: 32px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    margin-bottom: 12px;
  }
  
  p {
    font-size: 16px;
    color: var(--el-text-color-secondary);
    margin: 0;
  }
}

.register-form {
  .el-form-item {
    margin-bottom: 24px;
  }
  
  :deep(.el-input__wrapper) {
    padding: 0 15px;
    height: 48px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    transition: all 0.3s;
    
    &:hover, &:focus-within {
      box-shadow: 0 2px 12px rgba(102, 126, 234, 0.2);
    }
    
    .el-input__prefix {
      padding-right: 10px;
      color: #667eea;
    }
  }
  
  .captcha-input {
    display: flex;
    gap: 12px;
    
    .el-input {
      flex: 1;
    }
    
    .captcha-btn {
      white-space: nowrap;
      height: 48px;
      border-radius: 12px;
      background: #f5f7fa;
      color: #5a6bca;
      border: none;
      
      &:hover {
        background: #eef0f6;
      }
      
      &:disabled {
        background: #f5f7fa;
        color: #b1b1b1;
      }
    }
  }
  
  .register-btn {
    width: 100%;
    height: 52px;
    font-size: 18px;
    font-weight: 500;
    border-radius: 12px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
    }
    
    &:active {
      transform: translateY(0);
    }
  }
}

.register-footer {
  text-align: center;
  margin-top: 32px;
  font-size: 15px;
  color: var(--el-text-color-secondary);
  
  .el-link {
    margin-left: 8px;
    font-weight: 600;
  }
}

.social-register {
  margin-top: 40px;
  
  .divider {
    position: relative;
    text-align: center;
    margin-bottom: 30px;
    
    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 0;
      right: 0;
      height: 1px;
      background: var(--el-border-color-lighter);
    }
    
    span {
      background: white;
      padding: 0 20px;
      color: var(--el-text-color-secondary);
      font-size: 15px;
    }
  }
  
  .social-buttons {
    display: flex;
    justify-content: center;
    gap: 20px;
    
    .el-button {
      width: 56px;
      height: 56px;
      border-radius: 50%;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      font-size: 20px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
      }
    }
  }
}

.back-home-btn {
  position: fixed;
  top: 30px;
  left: 30px;
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  backdrop-filter: blur(10px);
  z-index: 10;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  
  &:hover {
    background: rgba(255, 255, 255, 0.3);
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
  }
}

@media (max-width: 600px) {
  .register-card {
    padding: 30px;
  }
  
  .register-header {
    h2 {
      font-size: 28px;
    }
    
    p {
      font-size: 14px;
    }
  }
  
  .back-home-btn {
    top: 20px;
    left: 20px;
    width: 42px;
    height: 42px;
  }
}
</style>
